﻿using System.Linq;
using Daemon.Common;
using Daemon.Common.Helpers;
using Daemon.Infrustructure.EF;
using Daemon.Repository.EF.Enums;
using Daemon.Repository.Contract;
using Daemon.Model;
using System;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace Daemon.Repository.EF
{
	public class TakeAwayGoodRuleRepository : Repository<TakeAwayGoodRule>, ITakeAwayGoodRuleRepository
	{
		private readonly ITakeAwayRuleDetailRepository _takeAwayRuleDetailRepository;

		protected override Expression<Func<TakeAwayGoodRule, int>> PrimaryKeyExpression => r => r.Id;

		public TakeAwayGoodRuleRepository(ApiDBContent context, ITakeAwayRuleDetailRepository takeAwayRuleDetailRepository) : base(context)
		{
			_takeAwayRuleDetailRepository = takeAwayRuleDetailRepository;
		}

		protected override IEnumerable<TakeAwayGoodRule> IncludeRelationships(IEnumerable<TakeAwayGoodRule> entities, ApiDBContent db)
		{
			SetRuleDetail(entities);

			return base.IncludeRelationships(entities, db);
		}

		private void SetRuleDetail(IEnumerable<TakeAwayGoodRule> entities)
		{
			if (!RouteParameterHelper.CheckRouteParameter(RelationshipNames, TakeAwayGoodRuleRelationShipEnum.RuleDetail))
			{
				return;
			}

			var ruleIds = entities.Select(r => r.Id).ToList();
			_takeAwayRuleDetailRepository.SetRelationships(new List<Model.Entities.Relationship>() { new Model.Entities.Relationship() { Name = TakeAwayRuleDetailRelationShipEnum.DetailValue.ToString() } });
			var dicRuleDetail = _takeAwayRuleDetailRepository.IncludeRelationships(Context.TakeAwayRuleDetail.Where(r => ruleIds.Contains(r.RuleId))).ToList().GroupBy(r => r.RuleId).ToDictionary(r => r.Key, r => r.ToList());
			foreach (var entity in entities)
			{
				if (dicRuleDetail.TryGetValue(entity.Id, out List<TakeAwayRuleDetail> ruleDetail))
				{
					entity.Values = ruleDetail;
				}
			}
		}
	}
}
